// import { useState } from 'react';
// import { getWeekday } from '@/utils/getDay';
import { useEffect, useState } from 'react';
import { FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import CenterModel from './CenterModel';
import CurrentDayData from './CurrentDayData';
import DayPlusMemberAdd from './DayPlusMemberAdd';
import DayRevenueData from './DayRevenueData';
import STYLE from './index.less';
import MapContainer from './MapContainer';
import OperationalDiff from './OperationalDiff';
import OrderType from './OrderType';
import PayType from './PayType';
import RecordFeedBackForm from './RecordFeedbackForm';
import TimeDurationRate from './TimeDurationRate';
import TodayParkingData from './TodayParkingData';
import TopPayRate from './Top3PayRate';
import UserData from './UserData';
import { throttle } from 'lodash';
import type { AnalysisResult, OverviewResult } from './types';
import { getVisualOverview, getVisualAnalysis } from './service';
import moment from 'moment';

const IntellectiveVisual = () => {
  const [tab_data] = useState([
    { index: 0, name: '数据总览' },
    // { index: 1, name: '设备监控' },
    { index: 1, name: '运营分析' },
  ]);
  const [wrapBox, setwrapBox] = useState<HTMLElement | null>(null);
  // const [homePage, setHomePage] = useState<HTMLElement | null>(null);
  const [center, setCenter] = useState<[number, number]>([120.384, 30.344]); //坐标点击的点击位置 （纬度取决
  const [isFullScreen, setIsFullScreen] = useState<boolean>(false);
  // const [parkingLots, setParkingLots] = useState<OverviewParkingLots[]>([]);
  const [overViewResult, setOverViewResult] = useState<OverviewResult | null>(null);
  const [analysisResult, setAnalysisResult] = useState<AnalysisResult | null>(null);
  const [index, setIndex] = useState<number>(0);
  const [date, setDate] = useState(moment().format('YYYY-MM-DD dddd HH:mm')); //日期格式化的变量 保存当前日期到变量中。;
  // const [time] = useState<string>('15:18');

  const clickTab = (index1: number) => {
    setIndex(index1);
  };
  useEffect(() => {
    if (index === 1) {
      getVisualAnalysis()
        .then((res) => {
          if (res.success) {
            // console.log(res.data, '数据');
            setAnalysisResult(res.data);
          } else {
            message.error({
              content: res?.message || '获取分析数据失败',
              key: 'analysis',
            });
          }
        })
        .catch((err) => {
          message.error({
            content: err || '获取分析数据失败',
            key: 'analysis',
          });
        });
    }
  }, [index]);
  useEffect(() => {
    const tempBox = document.getElementById('visual_plat');
    setwrapBox(tempBox);
    // const home = document.getElementById('visual_home');
    // setHomePage(home);
    const timer = setInterval(() => {
      setDate(moment().format('YYYY-MM-DD dddd HH:mm'));
    }, 1000);

    return () => {
      clearInterval(timer);
    };
  }, []); //

  useEffect(() => {
    getVisualOverview(...center).then((res) => {
      if (res.success) {
        setOverViewResult(res.data);
        // console.log(res.data);
      }
    });
    const time1 = setInterval(() => {
      getVisualOverview(...center).then((res) => {
        if (res.success) {
          setOverViewResult(res.data);
          // console.log(res.data);
        }
      });
    }, 1000 * 60 * 60);
    return () => {
      clearInterval(time1);
    };
  }, [center]);

  const handleCenter = (data: [number, number]) => {
    setCenter(data);
  };

  document.addEventListener('fullscreenchange', function () {
    if (!document.fullscreenElement) {
      // console.log('页面退出了全屏模式');
      setIsFullScreen(false);
    }
  });
  if (wrapBox !== null) {
    const iniNumX = wrapBox.parentElement?.clientWidth || 1920;
    const iniNumY = (1080 * iniNumX) / 1920;
    wrapBox.style.transform = `scaleX(${iniNumX / 1920}) scaleY(${iniNumY / 1080})`;
    const handler = throttle(() => {
      const numX = wrapBox.parentElement?.clientWidth || 1920;
      // const numY = wrapBox.parentElement?.clientHeight || 1080;
      const numY = (1080 * numX) / 1920;
      wrapBox.style.transform = `scaleX(${numX / 1920}) scaleY(${numY / 1080})`;
      // console.log(numY);
    });
    window.addEventListener('resize', handler);
  }
  return (
    <div className="visual_page" id="visual_home">
      <div className={STYLE.visualPlatform} id="visual_plat">
        <div className={STYLE.top}>
          <div className={STYLE.left}>
            <div className={STYLE.left_title}>智慧停车可视化平台</div>
            <div className={STYLE.to_right_bar}>
              <img className={STYLE.right_arrow} src="/visual/three_arrow.svg" alt="" />
              <div className={STYLE.line} />
              <div className={STYLE.dot} />
            </div>
            <div className={STYLE.tab_bar}>
              {tab_data.map((item) => {
                return (
                  <div
                    className={index === item.index ? STYLE.active : STYLE.tab_item}
                    key={item.index}
                    onClick={() => clickTab(item.index)}
                  >
                    {item.name}
                  </div>
                );
              })}
            </div>
          </div>
          <div className={STYLE.time}>
            <div className={STYLE.date}>{date}</div>
            {/* <div className={STYLE.border} />
            <div className={STYLE.day_time}>{`${getWeekday(date)} ${time}`}</div> */}
          </div>
        </div>
        <div className={STYLE.top_bottom_img} />
        <div className={STYLE.content}>
          {index === 0 ? (
            <div className={STYLE.content_1}>
              <div className={STYLE.right}>
                <div className={STYLE.map}>
                  <MapContainer
                    parkingLots={overViewResult?.parkingLots ? overViewResult.parkingLots : []}
                    onCenterChange={handleCenter}
                  />
                </div>
                <DayRevenueData
                  payableAmountList={
                    overViewResult?.payableAmountList
                      ? overViewResult.payableAmountList.map((item) => item / 100)
                      : []
                  }
                  paymentAmountList={
                    overViewResult?.paymentAmountList
                      ? overViewResult.paymentAmountList.map((item) => item / 100)
                      : []
                  }
                />
              </div>
              <div className={STYLE.left}>
                <CurrentDayData
                  tPayableAmount={overViewResult?.tPayableAmount || 0}
                  tPaymentAmount={overViewResult?.tPaymentAmount || 0}
                  tParkingTime={overViewResult?.tParkingTime || 0}
                  tTotalOrder={overViewResult?.tTotalOrder || 0}
                />
                <UserData
                  registerWxUser={overViewResult?.registerWxUser || []}
                  activeWxUser={overViewResult?.activeWxUser || []}
                />
                <TodayParkingData
                  turnoverRates={overViewResult?.turnoverRates || []}
                  userRates={overViewResult?.useRates || []}
                />
              </div>
            </div>
          ) : (
            ''
          )}
          {index === 1 ? (
            <div className={STYLE.content_2}>
              <div className={STYLE.left}>
                {/* <TestChart /> */}
                <DayPlusMemberAdd weekMember={analysisResult?.weekMember || []} />
                <OperationalDiff
                  weekCompare={analysisResult?.weekCompare || null}
                  todayCompare={analysisResult?.todayCompare || null}
                />
                <TimeDurationRate parkingTimes={analysisResult?.parkingTimes || []} />
              </div>
              <div className={STYLE.middle}>
                <CenterModel monthOrders={analysisResult?.monthOrders || null} />
                <RecordFeedBackForm entryRates={analysisResult?.entryRates || []} />
              </div>
              <div className={STYLE.right}>
                <TopPayRate payRates={analysisResult?.payRates || []} />
                <OrderType monthOrders={analysisResult?.monthOrders || null} />
                <PayType dayPayModeCount={analysisResult?.dayPayModeCount || []} />
              </div>
            </div>
          ) : (
            ''
          )}
          {index === 2 ? (
            <div className={STYLE.content_3}>
              <div className={STYLE.left} />
              <div className={STYLE.middle} />
              <div className={STYLE.right} />
            </div>
          ) : (
            ''
          )}
        </div>
        <div className={STYLE.fullscreen}>
          <Button
            title="全屏"
            type="link"
            style={{ opacity: 0.6 }}
            onClick={() => {
              const dom = document?.getElementById('visual_home');
              if (dom && !isFullScreen) {
                if (dom.requestFullscreen) {
                  dom.requestFullscreen();
                  // @ts-ignore
                } else if (dom.webkitRequestFullScreen) {
                  // @ts-ignore
                  dom.webkitRequestFullScreen();
                  // @ts-ignore
                } else if (dom.mozRequestFullScreen) {
                  // @ts-ignore
                  dom.mozRequestFullScreen();
                  // @ts-ignore
                } else if (dom.msRequestFullscreen) {
                  // @ts-ignore
                  dom.msRequestFullscreen();
                } else {
                  message.warn({
                    content:
                      '当前浏览器不支持全屏浏览，请尝试以下浏览器中的某一个：Chrome、Firefox、Safari',
                    key: 'no-fullscreen',
                  });
                }
              } else if (document.exitFullscreen) {
                document.exitFullscreen();
                // @ts-ignore
              } else if (document.webkitExitFullscreen) {
                // @ts-ignore
                document.webkitExitFullscreen();
                // @ts-ignore
              } else if (document.mozCancelFullScreen) {
                // @ts-ignore
                document.mozCancelFullScreen();
                // @ts-ignore
              } else if (document.msExitFullscreen) {
                // @ts-ignore
                document.msExitFullscreen();
              } else {
                message.warn({
                  content: '如果无法点击退出全屏，请尝试点击键盘Esc键',
                  key: 'no-fullscreen',
                });
              }
              setIsFullScreen(!isFullScreen);
            }}
          >
            {isFullScreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
          </Button>
        </div>
      </div>
    </div>
  );
};
export default IntellectiveVisual;
